package net.openl10n.mdf;


import java.util.List;

import net.openl10n.document.api.IContainer;

import com.google.common.collect.ImmutableList;

public class Container extends AbstractDocumentPart implements IContainer{

	private final ImmutableList<PartId> children;
	
	private final int hashCode;
	
	public Container(PartId id, Long version, List<PartId> children) {
		super(id, version);
		if(children == null){
			throw new IllegalArgumentException("children cannot be null");
		}
		if(children instanceof ImmutableList<?>)
			this.children = (ImmutableList<PartId>) children;
		else
			this.children = ImmutableList.copyOf(children);
		
		this.hashCode = generateHashCode();
	}
	
	@Override
	public final ImmutableList<PartId> getChildren() {
		return children;
	}

	
	@Override
	public final boolean equals(Object obj) {
		if(obj == null) return false;
		if( !(obj instanceof Container) ) return false;
		Container other = (Container) obj;
		return ( super.equals(other) 
				&& other.children.equals(children) );
	}
	
	@Override
	public final int hashCode() {
		return hashCode;
	}
	
	private int generateHashCode() {
	    int hash = 1;
	    hash = super.hashCode();
	    // note that we can cache the children hashCode as all elements stored within the
	    // list are also immutable
	    hash = hash * 31 + children.hashCode();
	    return hash;
	}
	
}
